const puppeteer = require('puppeteer');

async function generatePDF(url, outputPath, options) {
  try {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    
    // 使用环境变量或默认超时
    const timeout = process.env.PDF_TIMEOUT || 8000;
    await page.setDefaultTimeout(timeout);
    
    // 添加关键的waitUntil选项
    await page.goto(url, { waitUntil: 'networkidle0' });
    
    // 默认PDF选项
    const defaultOptions = {
      format: 'A4',
      printBackground: true,
      margin: { top: '60px', right: '10px', bottom: '10px', left: '60px' }, // 恢复原始边距
      landscape: false,
      scale: 1.0 // 恢复默认缩放
    };
    
    // 合并用户提供的选项
    const finalOptions = { ...defaultOptions, ...options, path: outputPath };
    
    await page.pdf(finalOptions);
    console.log(`PDF已保存至 ${outputPath}`);
    await browser.close();
  } catch (err) {
    console.error('生成PDF失败:', err);
    process.exit(1);
  }
}

// 参数处理
const url = process.argv[2] || 'http://localhost:6006/iframe.html?viewMode=story&id=crepe-frame--wiki-value';
const outputPath = process.argv[3] || 'hn.pdf';

generatePDF(url, outputPath);
